package com.cghs.ac.info;

import java.io.IOException;
import java.io.RandomAccessFile;
import java.security.PublicKey;

import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Build;

import com.cghs.ac.utils.ShellUtils;
import com.cghs.ac.utils.ShellUtils.CommandResult;

public class SystemInfoUtils {
	public static final String LOG_TAG = "SystemInfoUtils";
	
	/**
	 * get the android dns by prop .
	 * it contains "net.dns1" and "net.dns2"
	 * 
	 * @return 
	 */
	
	public static String getDNSServer() {
		CommandResult commandResult = ShellUtils.execCommand("getprop net.dns1", false, true);
		if (commandResult.result == 0) {
			return commandResult.successMsg;
		} else {
			return commandResult.errorMsg;
		}
	}
	
	/**
	 * get the android version.
	 * 
	 * @return
	 */
	public static String getAndroidVersion() {
		return Build.VERSION.SDK_INT+"";
	}
	
	
	/**
	 * get the device produce name 
	 * @return
	 */
	public static String getProduceName() {
		return Build.MODEL;
	}
	
	/**
	 * 
	 * @return
	 */
	public static float getCpuRate() {

        try {
            RandomAccessFile reader = new RandomAccessFile("/proc/stat", "r");
            String load = reader.readLine();
            String[] toks = load.split(" ");
            long idle1 = Long.parseLong(toks[5]);
            long cpu1 = Long.parseLong(toks[2]) + Long.parseLong(toks[3])
                    + Long.parseLong(toks[4]) + Long.parseLong(toks[6])
                    + Long.parseLong(toks[7]) + Long.parseLong(toks[8]);
            try {
                Thread.sleep(360);
            } catch (Exception e) {
            }
            reader.seek(0);
            load = reader.readLine();
            reader.close();
            toks = load.split(" ");
            long idle2 = Long.parseLong(toks[5]);
            long cpu2 = Long.parseLong(toks[2]) + Long.parseLong(toks[3])
                    + Long.parseLong(toks[4]) + Long.parseLong(toks[6])
                    + Long.parseLong(toks[7]) + Long.parseLong(toks[8]);

            return (int) (100 * (cpu2 - cpu1) / ((cpu2 + idle2) - (cpu1 + idle1)));

        } catch (IOException ex) {
            ex.printStackTrace();
        }
        return 0;

    }
    
    
    public static String getMemRate() {

        try {
            RandomAccessFile reader = new RandomAccessFile("/proc/meminfo", "r");
            String total = reader.readLine();
            String free = reader.readLine();
            
            String[] toks = total.split("\\s+");
            String totalMem = toks[1]+toks[2]; 
            
            String[] toks2 = free.split("\\s+");
            String freeMem = toks2[1]+toks2[2];
            reader.close();

            return freeMem+"/"+totalMem;

        } catch (IOException ex) {
            ex.printStackTrace();
        }
        return "";

    }
	
}
